﻿using System;
using System.Collections.Generic;

namespace Simp.CodeModel.CoreVisitors
{
	/// <summary>Visitor replacing <see cref="ScopeFunction"/> by their equivalent.</summary>
	public class UnscopeFunctionVisitor : IFunctionVisitor
	{
		private readonly IFunction[] _knownFunctionList;

		/// <summary>Constructor taking the known functions in parameter.</summary>
		/// <param name="knownFunctionList"/>
		public UnscopeFunctionVisitor(IFunction[] knownFunctionList)
		{
			if (knownFunctionList == null)
			{
				throw new ArgumentNullException("knownFunctionList");
			}
			_knownFunctionList = knownFunctionList;
		}

		#region IFunctionVisitor Members
		IFunction IFunctionVisitor.Visit(IFunction function)
		{
			ScopeFunction scopeFunction = function as ScopeFunction;

			if (scopeFunction == null)
			{
				return function.AcceptVisitor(this);
			}
			else
			{	//	Flatten down the scope
				EvaluationContext evaluationContext = EvaluationContext.WithPackages(_knownFunctionList);

				evaluationContext.Integrate(scopeFunction.DefinitionList);

				IFunction flattenFunction = evaluationContext.Evaluate(scopeFunction.ReturnFunction, true);

				return flattenFunction;
			}
		}
		#endregion
	}
}